package server.Handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import protocol.PacketCodeC;
import protocol.request.LoginRequestPacket;
import protocol.response.LoginResponsePacket;
import session.Session;
import util.LoginUtil;
import util.SessionUtil;

import java.util.Date;
import java.util.UUID;

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket requestPacket) throws Exception {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();

        if (!valid(requestPacket)){
            loginResponsePacket.setSuccess(false);
            loginResponsePacket.setReason("用户名或密码错误");
            System.out.println(new Date() + ":登录失败");
        }else {
            loginResponsePacket.setSuccess(true);
            System.out.println(new Date() + "[" + requestPacket.getUsername() + "]" + ":登录成功");
            String userId = randomUserId();
            loginResponsePacket.setUserId(userId);
            loginResponsePacket.setUserName(requestPacket.getUsername());
            SessionUtil.markAsLogin(ctx.channel());
            SessionUtil.bindSession(new Session(userId, requestPacket.getUsername()), ctx.channel());
        }
        ctx.channel().writeAndFlush(loginResponsePacket);
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
    }

    private static String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtil.unBindSession(ctx.channel());
        super.channelInactive(ctx);
    }
}
